package com.htl.exampro.base.utils;

import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Map;

public class UserUtil {

    public final static String TOKEN = "TOKEN$$";
    public static final String USER_ID = "user_id";
    public static final String USERNAME = "username";
    public static final String REAL_NAME = "real_name";
    public static final String EMAIL = "email";
    public static final String PHONE = "phone";
    public static final String ROLE = "role";
    public static final String GENDER = "gender";
    public static final String BIRTHDAY = "birthday";

    public static String getUserId() {
        return get(USER_ID);
    }

    public static String getUsername() {
        return get(USERNAME);
    }

    public static String getRealName() {
        return get(REAL_NAME);
    }

    public static String getEmail() {
        return get(EMAIL);
    }

    public static String getPhone() {
        return get(PHONE);
    }

    public static String getRole() {
        return get(ROLE);
    }

    public static String getGender() {
        return get(GENDER);
    }

    public static String getBirthday() {
        return get(BIRTHDAY);
    }

    private static String get(String key) {
        try {
            Map<String, Object> map = (Map<String, Object>) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return map.get(key).toString();
        } catch (Exception e) {
            return null;
        }
    }

    public static String getTokenKey() {
        String userId = getUserId();
        return userId == null ? null : getTokenKey(Long.valueOf(userId));
    }

    public static String getTokenKey(Long userId) {
        return TOKEN + userId;
    }
}
